const app = getApp();
var api = require("../../api/api.js");
var utils = require("../../utils/utils.js");
var event = require("../../event/event.js");
var storageManage = require("../../manage/storageManage.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    params: [],
    couponParams: [],
    dataId: [],
    user_id: '',
    idArr: [],
    remark: '',
    address_id: '',
    order_no: '',
    payTapState: false,
    user_type: '',
    clientData: {},
    addrData: {},
    animationData: "",
    paymentCenterAnimationData: '',
    address: '',
    name: '',
    phone: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

    //页面高度
    wx.getSystemInfo({
      success: function (res) {
        that.data.windowHeight = res.windowHeight;
      }
    });

    //添加地址的事件响应（销售）
    event.on('addressClient', this, function (data) {
      that.setData({
        clientData: data,
        addrData: data
      })
    });
    //修改地址的事件响应销售）
    event.on('editAddressClient', this, function (data) {
      console.log(data)
      that.setData({
        addrData: data
      })
    });
    let params = JSON.parse(options.params);
    // let params = [{ "sku_id": "10", "amount": 1, "commodity_id": "2018032900000004" }]
    this.setData({
      params: params,
      user_type: storageManage.getGlobalConfig().user_type
    })
    for (var i = 0; i < params.length; i++) {
      this.data.dataId.push(params[i].sku_id);
      this.data.idArr.push(params[i].commodity_id);
      var key = params[i].sku_id.toString();
      this.data.couponParams.push({
        [key]: params[i].amount
      })
    }
    wx.showLoading()
    api.default.api('preview_order', { "skus": params }, this.successCallback, this.errorCallback);
  },


  successCallback: function (e) {
    wx.hideLoading()
    this.setData({
      list: e.data.skus,
      default_address: e.data.default_address,
      comm_cnt: e.data.comm_cnt,
      commodity_cost: e.data.commodity_cost

    });
  },
  errorCallback: function (e) {
    console.log(e)
  },
  onReady: function () {
    //获得modalContainer组件
    this.modalContainer = this.selectComponent("#modalPay");
  },
  //结算生产订单且弹出选择支付方式
  showPay: function (e) {

    api.default.send_template(e);
    var that = this;
    var paymentState = this.data.paymentState;

    if (that.data.user_type != 1) {
      if (utils.isEmpty(this.data.default_address.address_id)) {
        toastShow("请填写收获地址")
        return;
      }
    } else {
      if (utils.isEmpty(this.data.clientData.user_id)) {
        toastShow("请选择门店")
        return;
      }
    }

    var payload = {
      "detail": that.data.params,
      "remark": that.data.remark
    }
    if (that.data.user_type == 0) {
      payload.address_id = that.data.default_address.address_id;
      payload.user_id = storageManage.getServiceUser().user_id
    } else {
      payload.user_id = that.data.addrData.user_id;
      payload.address = that.data.addrData.address;
      payload.name = that.data.addrData.name;
      payload.phone = that.data.addrData.phone;
    }
    api.default.api('create_order', payload, this.createSuccessCallback, this.createErrorCallback);
  },

  //创建订单返回值
  createSuccessCallback: function (data) {
    var that = this;
    var payload={
      order_no: data.data.order_no,
      balance: data.data.balance,
      commodity_cost: that.data.commodity_cost
    }
    that.setData({
      order_no: data.data.order_no,
      balance: data.data.balance
    })
    api.default.api('delete_cart', {
      "sku_id": this.data.dataId
    }, function (data) {
      event.notify('cart', '');

      that.modalContainer.showModalContainer(payload);
    }, function (data) {
      console.info("删除购物车失败")
    })
  },
  createErrorCallback: function () {
    console.info("创建订单失败")
  },

  //组件支付完成回调
  _pay: function (e) {

    //支付成功返回支付方式的状态值
    var paymentState = e.detail.paymentState; 
    if (paymentState == 0) {
      wx.reLaunch({
        url: '../orderFinished/orderFinished?state=1'
      })

    } else if (paymentState == 3) {
      wx.reLaunch({
        url: '../orderFinished/orderFinished?state=0'
      })

    } else {
      wx.reLaunch({
        url: '../orderFinished/orderFinished?state=1'
      })
    }
  },
  remarkChange:function(e){
    this.setData({
      remark: e.detail.value
    })
  },
  /**
   * sele addr
   */
  seleAddr: utils.throttle(function () {
    event.on('addr', this, function (addr) {
      console.log("addr receive event");
      this.updata(addr);
    });

    wx.navigateTo({
      url: '../address/addr_list/addr_list?form_outer=' + true + '&idArr=' + this.data.idArr.toString(),
    })

  }),
  addr_add: utils.throttle(function () {
    wx.navigateTo({
      url: '../address/addr_add/addr_add?idArr=' + this.data.idArr.toString(),
    })
  }),

  addressClient: utils.throttle(function () {
    wx.navigateTo({
      url: '../addressClient/addressClient'
    })
  }),
  editAddressClient: utils.throttle(function () {
    var curAddr = this.data.addrData;
    wx.navigateTo({
      url: '../address/addr_add/addr_add?curAddr=' + JSON.stringify(curAddr)
    });
  }),


  updata: function (addr) {
    console.log("...receive " + JSON.stringify(addr));
    this.setData({
      default_address: addr,
    });

  }
})
function toastShow(text, state) {
  wx.showToast({
    title: text,
    icon: state ? state : 'none',
    duration: 1000
  })
}